/**
 * <p>文件名:		ImageOpsTest.java</p>
 * <p>版权:		CopyrightTag</p>
 * <p>公司:		CompanyTag</p>
 * @author		周华彬(zhouhuabin@chinatransinfo.com, zhou_hua_bin@163.com)
 */

package com.palmgo.utils.drawer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.palmcity.rtti.util.FileUtils;
import com.palmgo.utils.drawer.basic.DeformationAgient;
import com.palmgo.utils.drawer.basic.JSON2BeanUtils;
import com.palmgo.utils.drawer.model.HighwayTrafficBean;

/**
 * <p>
 * ImageOpsTest
 * </p>
 * <p>
 * TODO
 * </p>
 * @author 周华彬(zhouhuabin@chinatransinfo.com, zhou_hua_bin@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhouhuabin</td>
 *          <td>2015年11月9日 下午6:45:43</td>
 *          </tr>
 *          <tr>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          </tr>
 *          </table>
 */

public class ImageRenderMain extends Application {
	/** 变量:TODO,类型:Logger */
	private static Logger log = LoggerFactory.getLogger(TrafficRenderThread.class);
	// 图片大小
	private static final int IMAGE_WIDTH = 480;
	private static final int IMAGE_HEIGHT = 480;
	
	/** 变量:渲染线程类,类型:TrafficRenderThread */
	private TrafficRenderThread render;
	/** 变量:任务列表,类型:List<HighwayTrafficBean> */
	public  final static List<HighwayTrafficBean> taskList = new LinkedList<HighwayTrafficBean>();
	public static void main(String[] args) {
		System.out.println("Hello World!!!");
		String jsonHighwayStr1 = FileUtils.fileToString(new File("testdata/100106.xml"), FileUtils.CONST_UTF8_CHARSET);
		JSONObject object1 = XML.toJSONObject(jsonHighwayStr1);
		JSONObject jsonHighway1 = (JSONObject) object1.get("highwaytraffic");
		HighwayTrafficBean htb1 = JSON2BeanUtils.comperJson2Bean(jsonHighway1, HighwayTrafficBean.class);
		htb1.setSegmentid("100106");
		htb1.setFileSavePath("D:\\var\\highway\\intercity\\20151113\\100106.png");
		taskList.add(htb1);
		String jsonHighwayStr2 = FileUtils.fileToString(new File("testdata/100605.xml"), FileUtils.CONST_UTF8_CHARSET);
		JSONObject object2 = XML.toJSONObject(jsonHighwayStr2);
		JSONObject jsonHighway2 = (JSONObject) object2.get("highwaytraffic");
		HighwayTrafficBean htb2 = JSON2BeanUtils.comperJson2Bean(jsonHighway2, HighwayTrafficBean.class);
		htb2.setSegmentid("100605");
		htb2.setFileSavePath("D:\\var\\highway\\intercity\\20151113\\100605.png");
		taskList.add(htb2);
		String jsonHighwayStr3 = FileUtils.fileToString(new File("testdata/100610.xml"), FileUtils.CONST_UTF8_CHARSET);
		JSONObject object3 = XML.toJSONObject(jsonHighwayStr3);
		JSONObject jsonHighway3 = (JSONObject) object3.get("highwaytraffic");
		HighwayTrafficBean htb3 = JSON2BeanUtils.comperJson2Bean(jsonHighway3, HighwayTrafficBean.class);
		htb3.setSegmentid("100610");
		htb3.setFileSavePath("D:\\var\\highway\\intercity\\20151113\\100610.png");
		taskList.add(htb3);
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) {
		log.info("开始绘制主舞台：");
		primaryStage.setTitle("高速变形图绘制");
		Group root = new Group();
		Canvas canvas = new Canvas(IMAGE_WIDTH, IMAGE_HEIGHT);
		root.getChildren().add(canvas);
		Scene scene = new Scene(root, IMAGE_WIDTH, IMAGE_HEIGHT);
		primaryStage.setScene(scene);
		primaryStage.show();
		GraphicsContext gc = canvas.getGraphicsContext2D();
		
		/* */
		DeformationAgient agient = new DeformationAgient();
		agient.setFontSize(16);
		agient.setRoadWidth(30);
		render = new TrafficRenderThread(agient, gc, scene);
		render.submitSegmentTrafficList(taskList);
		Executors.newSingleThreadExecutor().execute(render);
		
		//测试用:一段时间过后自动绘制
		{
			ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor();
			schedule.schedule(new Runnable() {
			@Override
			public void run() {
				synchronized (render) {
					render.notifyAll();
				}
			}
		},10,TimeUnit.SECONDS);
		}
	}

	/**
	 * 保存图片到指定路径，只能是png格式
	 * @param writableImage void
	 */
	public boolean saveImage2File(WritableImage writableImage, String filePath) {
		try {
			BufferedImage image = SwingFXUtils.fromFXImage(writableImage, null);
			OutputStream output = new FileOutputStream(filePath);
			ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
			ImageIO.write(image, "PNG", imageOut);
			imageOut.close();
			output.flush();
			output.close();
			return true;
		} catch (Exception e) {
			System.err.println("图片产生出现错误：" + e.toString());
			return false;
		}
	}

	

	/**
	 * 绘制简单的方格图
	 * @param scene
	 * @param gc2
	 * @return WritableImage
	 */
	private WritableImage drawImageData(Scene scene, GraphicsContext gc2) {
		int image_height = 10;
		int image_width = 10;
		boolean on = true;
		int i = 0;
		byte imageData[] = new byte[image_width * image_height * 3];
		for (int y = 0; y < image_height; y++) {
			int r = y * 255 / image_height;
			for (int x = 0; x < image_width; x++) {
				int g = x * 255 / image_width;
				imageData[i] = (byte) r;
				imageData[i + 1] = (byte) g;
				i += 3;
			}
		}
		PixelWriter pixelWriter = gc2.getPixelWriter();
		PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteRgbInstance();
		for (int y = 50; y < 150; y += image_height) {
			for (int x = 50; x < 150; x += image_width) {
				if (on) {
					pixelWriter.setPixels(x, y, image_width, image_height, pixelFormat, imageData, 0, image_width * 3);
				}
				on = !on;
			}
			on = !on;
		}
		gc2.applyEffect(new DropShadow(20, 20, 20, Color.GRAY));
		return scene.snapshot(null);
	}
}
